#!/usr/bin/env ruby

# fiflist - Find In Files List Lines
# this script iterates over each file returned by `fif`
#     and displays each matching line


SEARCH_PATH     = ARGV[0]
SEARCH_TERM     = ARGV[1]
EXCLUDE_TERM    = ARGV[2]
COINCIDENT_TERM = ARGV[3]
USAGE           = "USAGE:\n"                                                                            +
                  "\tfiflist <path/to/search> <search-term> [ <exclude-term> ] [ <coincident-term> ]\n" +
                  "DESCRIPTION:\n"                                                                      +
                  "\tfind search-term in files displaying each matching line\n"
unless SEARCH_TERM ; print USAGE ; exit ; end ;


def report_matches file , term
  lines = `cat #{file} | grep -n "#{term}"`.split "\n"
  lines.each { | line | print "   #{file}:#{line.sub ':' , ":\n     "}\n" }
end


fif_cmd = "fif \"#{SEARCH_PATH}\" \"#{SEARCH_TERM}\" \"#{EXCLUDE_TERM}\""
files   = `#{fif_cmd}`.split "\n"

files.each do | file |
  print "\nin #{file}:\n"
  report_matches file , SEARCH_TERM
  report_matches file , COINCIDENT_TERM unless COINCIDENT_TERM.nil?
end
